package com.gitee.elf.core.entity

import com.gitee.elf.core.data.DataString
import com.gitee.elf.core.entity.trait.Trait
import org.bukkit.Location
import org.bukkit.World
import org.bukkit.entity.Entity
import taboolib.library.reflex.Reflex.Companion.invokeConstructor

class EntityInstance(val id: Long, val owner: Entity, val themeId: String) {

    val theme: EntityTheme?
        get() = EntityManager.getEntityTheme(themeId)

    val ownerLocation: Location
        get() = owner.location

    val ownerWorld: World
        get() = owner.world

    var metadataContainer = MetadataContainer(this)

    val mapping: Class<ProxyEntity<*>>?
        get() = theme?.entityMapping

    var mappingInstance: ProxyEntity<*>? = null

    var status = EntityStatus.INITIAL
        set(value) {
            // 在初始化完成之后 初始化trait
            if (status == EntityStatus.INITIAL && value != EntityStatus.INITIAL) {
                traits = Trait.createTraits(this)
            }
            field = value
        }

    lateinit var traits: Map<String, Trait>

    /**
     * 召唤
     */
    fun spawn() {
        status = EntityStatus.SPAWN
        mappingInstance = mapping?.invokeConstructor(this)
        mappingInstance?.onSpawn()
        status = EntityStatus.ACTIVE
    }

    /**
     * 销毁
     */
    fun destroy() {
        mappingInstance?.onDestroy()
        mappingInstance = null
        status = EntityStatus.STANDBY
    }

    fun metaUpdate(id: String, value: MetadataContainer.Data) {

    }

    /**
     * 跨服复位
     */
    fun reset() {
        if (metadataContainer.getValue<DataString>("status")?.value == "ACTIVE") {
            spawn()
        }
    }


}